<template>
  <div class="app-container">
    <div class="mb-12">
      <el-button v-hasPermi="['system:role:add']" type="primary" @click="handleAdd">添加角色</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="roleList"
    >
      <el-table-column label="ID" prop="id" align="center" />
      <el-table-column
        label="角色名称"
        prop="display_name"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="角色标识"
        prop="name"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="created_at"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding"
      >
        <template v-if="scope.row.roleId !== 1" slot-scope="scope">
          <el-button
            v-hasPermi="['system:role:edit']"
            size="mini"
            type="success"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['system:role:delete']"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="display_name">
          <el-input v-model="form.display_name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="name">
          <span slot="label">
            <el-tooltip
              content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
              placement="top"
            >
              <i class="el-icon-question" />
            </el-tooltip>
            角色标识
          </span>
          <el-input v-model="form.name" placeholder="请输入角色标识" />
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox
            v-model="menuExpand"
            @change="handleCheckedTreeExpand($event, 'menu')"
          >展开/折叠</el-checkbox>
          <el-checkbox
            v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'menu')"
          >全选/全不选</el-checkbox>
          <el-checkbox
            v-model="menuCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'menu')"
          >父子联动</el-checkbox>
          <el-tree
            ref="menuRef"
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            node-key="id"
            :check-strictly="!menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listRole,
  getRole,
  delRole,
  addRole,
  updateRole
} from '@/api/system/role'
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
  listMenu
} from '@/api/system/menu'

export default {
  name: 'Role',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      menuCheckStrictly: true,
      deptExpand: true,
      deptNodeAll: false,
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        name: undefined,
        display_name: undefined,
        description: undefined,
        permission_ids: []
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 表单校验
      rules: {
        display_name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入角色标识', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true
      listRole().then(data => {
        this.roleList = data
        this.loading = false
      })
    },
    /**
     * 根据id将数据组织成树状结构
     * @param ary 要组织的数据
     * @param pid 最顶层数据的id值
     * @param pidName 父id字段名
     * @returns {*}
     */
    formatToTree(ary, pid, pidName = 'parent_id') {
      return ary
        .filter((item) => item[pidName] === pid)
        .map((item) => {
          // 通过父节点ID查询所有子节点
          item.children = this.formatToTree(ary, item.id)
          return item
        })
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      listMenu().then((data) => {
        this.menuOptions = this.formatToTree(data, 0)
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menuRef.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menuRef.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      const checkedKeys = this.$refs.dept.getCheckedKeys()
      // 半选中的部门节点
      const halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      if (this.$refs.menuRef != undefined) {
        this.$refs.menuRef.setCheckedKeys([])
      }
      this.menuExpand = false
      this.menuNodeAll = false
      this.deptExpand = true
      this.deptNodeAll = false
      this.form = {
        name: undefined,
        display_name: undefined,
        description: undefined,
        permission_ids: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        const treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menuRef.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menuRef.setCheckedNodes(value ? this.menuOptions : [])
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : [])
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      this.menuCheckStrictly = !!value
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getMenuTreeselect()
      this.open = true
      this.title = '添加角色'
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset()

      await this.getMenuTreeselect()
      const detail = await getRole({
        id: row.id
      })
      const { role_permission_ids } = detail
      this.form = detail
      this.open = true
      this.title = '修改角色'

      setTimeout(()=> {
        this.$nextTick(() => {
          role_permission_ids.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.menuRef.setChecked(v, true, false)
            })
          })
        })
      }, 100)
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            this.form.permission_ids = this.getMenuAllCheckedKeys()
            updateRole(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            this.form.permission_ids = this.getMenuAllCheckedKeys()
            addRole(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm(`是否确认删除"${row.display_name}"吗？`)
        .then(function() {
          return delRole({
            id: row.id
          })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/role/export',
        {
          ...this.queryParams
        },
        `role_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>
